#ifndef QUERYRESULTMODEL_H
#define QUERYRESULTMODEL_H
#include "queryresult.h"
#include <QJsonObject>
#include <QJsonArray>
#include <QList>
#include <QAbstractItemModel>
#include <QColor>
#include <QStyledItemDelegate>
#include "querypackage.h"
#include <QSize>
#include <utility>
#include <QPainter>
#include <QApplication>
#include <QStyleOptionButton>
#include <QPainterPath>
#include <QMouseEvent>
class OneWayQueryResultModel;
class RndTripResultModel;
class TransferResultModel;
enum CustomRoles {
    OneWayResultPtrRole = Qt::UserRole + 1,
    TransferFirstRole = Qt::UserRole + 2,
    TransferSecondRole = Qt::UserRole+3,
    RndFirstRole = Qt::UserRole+4,
    RndSecondRole = Qt::UserRole+5,
    RefundResultPtrRole = Qt::UserRole + 4,
    OnTimeResultPtrRole = Qt::UserRole + 5
};
class QueryResultModel:public QAbstractItemModel
{
    Q_OBJECT
public:

    QueryResultModel(QueryPackage* cur = nullptr, QObject *parent = nullptr)
        : QAbstractItemModel(parent), current(cur) {}
    int columnCount(const QModelIndex &parent = QModelIndex()) const override {
        Q_UNUSED(parent);
        return 1; // ListView 仅需1列，忽略多列逻辑
    }

    // 【适配ListView】行数 = 数据列表长度
    int rowCount(const QModelIndex &parent = QModelIndex()) const override {
        if (parent.isValid()) return 0; // 扁平结构，无父子节点，父索引有效时行数为0
        return getRowCount();
    }
    QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override {
        if (parent.isValid() || row < 0 || row >= getRowCount() || column != 0) {
            return QModelIndex(); // 无效索引（父有效/行越界/列非0）
        }
        // 传递行号作为索引内部数据（列固定为0）
        return createIndex(row, 0, row);
    }
    QModelIndex parent(const QModelIndex &child) const override{
        Q_UNUSED(child);
        return QModelIndex();
    }
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override {
        // 校验索引有效性
        if (!index.isValid() || index.row() >= getRowCount() || index.column() != 0) {
            return QVariant();
        }

        switch (role) {
        case Qt::TextAlignmentRole:
            return Qt::AlignVCenter; // 文字垂直居中
        case Qt::SizeHintRole:
            return QSize(0, 60); // 行高默认60px（与委托 sizeHint 一致）
        }
        return getData(index,role);
    }

    QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override {
        Q_UNUSED(section);
        if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
            return "列车信息"; // 单列表头文本
        }
        return QVariant();
    }
    Qt::ItemFlags flags(const QModelIndex &index) const override {
        if (!index.isValid()) return Qt::NoItemFlags;
        return Qt::ItemIsSelectable | Qt::ItemIsEnabled; // 核心交互权限
    }
    // enum type{
    //     OneWay,
    //     RoundTrip,
    //     Tranfer,
    //     Refund,
    //     OnTime,
    //     CheckPoint,
    //     OnSale
    // };
    static QueryResultModel* getModel(QueryPackage* t);
    void setPage(int page){
        curpage = page;
    }
    QueryPackage* getQueryPackage(){
        return current;
    }
    int getPage(){return curpage;}
    int getSize(){return size;}

    virtual QVariant getData(const QModelIndex&,int)const = 0;
    virtual int getRowCount()const = 0;
    virtual void setResult(const QJsonObject &) = 0;
    virtual QAbstractItemDelegate* getDelegate(QObject* parent)const = 0;

signals:
    void RequestForQuery(QueryPackage*,int page,int size);
public slots:
    void OnRequestForQuery();
protected:
    QueryPackage* current = nullptr;
    int curpage = 1;
    int size = 10;
};
#include <QStyleOptionButton>
#include <QMouseEvent>
#include <QApplication>

class OneWayDelegate:public QStyledItemDelegate{
    Q_OBJECT
public:
    explicit OneWayDelegate(QObject *parent = nullptr)
        : QStyledItemDelegate(parent),
        m_padding(10),
        m_spacing(15),
        m_tagSize(20, 20), // 标签的默认大小
        m_btnText("预订"), // 按钮文本
        m_btnWidth(80),    // 按钮固定宽度（可调整）
        m_btnHeight(30)    // 按钮固定高度（可调整）
    {
        // 初始化字体
        m_timeFont.setBold(true);
        m_timeFont.setPixelSize(24);

        m_stationFont.setPixelSize(16);

        m_trainFont.setBold(true);
        m_trainFont.setPixelSize(20);

        m_seatFont.setPixelSize(14);
        target_role = OneWayResultPtrRole;
    }

    void setTargetRole(CustomRoles t){
        target_role = t;
    }
    void setResult(QueryResult* res){
        currentResult = res;
    }

    // 重写 editorEvent 处理鼠标交互（按钮 hover/按下/点击）
    bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override {
        Q_UNUSED(model);
        QueryResult* p1 = index.data(target_role).value<QueryResult*>();
        if (!p1) return QStyledItemDelegate::editorEvent(event, model, option, index);

        // 1. 重新计算按钮区域（必须和 paint 中完全一致！）
        const QRect itemRect = option.rect;
        int totalAvailableWidth = itemRect.width() - 2 * m_padding - 4 * m_spacing; // 多减1个spacing（座位区-按钮区间距）
        if (totalAvailableWidth < 150) totalAvailableWidth = 150;

        // 前3个区域宽度比例不变
        int departWidth = static_cast<int>(totalAvailableWidth * 0.20);
        int trainWidth = static_cast<int>(totalAvailableWidth * 0.25);
        int arriveWidth = static_cast<int>(totalAvailableWidth * 0.20);
        int remainingWidth = totalAvailableWidth - departWidth - trainWidth - arriveWidth; // 剩余35%

        // 拆分座位区和按钮区：座位区占剩余宽度 - 按钮宽度 - 间距
        int seatWidth = remainingWidth - m_btnWidth - m_spacing;
        if (seatWidth < 100) seatWidth = 100; // 座位区最小宽度限制

        // 计算各区域位置（和 paint 完全同步）
        QRect departArea = QRect(itemRect.x() + m_padding, itemRect.y() + m_padding, departWidth, itemRect.height() - 2 * m_padding);
        QRect trainArea = QRect(departArea.right() + m_spacing, departArea.top(), trainWidth, departArea.height());
        QRect arriveArea = QRect(trainArea.right() + m_spacing, departArea.top(), arriveWidth, departArea.height());
        QRect seatArea = QRect(arriveArea.right() + m_spacing, departArea.top(), seatWidth, departArea.height());
        // 按钮区：座位区右侧 + 间距，垂直居中
        QRect btnArea = QRect(seatArea.right() + m_spacing,
                              departArea.top() + (departArea.height() - m_btnHeight) / 2,
                              m_btnWidth, m_btnHeight);

        // 2. 处理鼠标事件
        switch (event->type()) {
        case QEvent::MouseMove: {
            // 鼠标悬浮：更新 hover 状态
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if (btnArea.contains(mouseEvent->pos())) {
                m_hoverIndex = index;
            } else {
                m_hoverIndex = QModelIndex();
            }
            // 刷新当前 item（更新按钮 hover 样式）
            if(const_cast<QWidget*>(option.widget)){
                const_cast<QWidget*>(option.widget)->update(option.rect);
            }
            break;
        }
        case QEvent::MouseButtonPress: {
            // 鼠标按下：更新 pressed 状态（仅响应左键）
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if (mouseEvent->button() != Qt::LeftButton) break;
            if (btnArea.contains(mouseEvent->pos())) {
                m_pressedIndex = index;
                if(const_cast<QWidget*>(option.widget)){
                    const_cast<QWidget*>(option.widget)->update(option.rect);
                }
            }
            break;
        }
        case QEvent::MouseButtonRelease: {
            // 鼠标释放：判断有效点击，发射信号
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if (mouseEvent->button() != Qt::LeftButton) break;
            // 条件：释放位置在按钮区 + 之前按下的是当前索引（避免误触）
            if (btnArea.contains(mouseEvent->pos()) && m_pressedIndex == index) {
                emit bookButtonClicked(p1); // 发射点击信号，传递 QueryResult*
            }
            m_pressedIndex = QModelIndex(); // 清空按下状态
            if(const_cast<QWidget*>(option.widget)){
                const_cast<QWidget*>(option.widget)->update(option.rect);
            }
            break;
        }
        case QEvent::Leave: {
            // 鼠标离开 item：清空 hover 状态
            m_hoverIndex = QModelIndex();
            if(const_cast<QWidget*>(option.widget)){
                const_cast<QWidget*>(option.widget)->update(option.rect);
            }
            break;
        }
        default:
            break;
        }

        return QStyledItemDelegate::editorEvent(event, model, option, index);
    }

    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
    {
        bool status = false;
        QueryResult* p1 = currentResult;
        if (!p1) {
            qDebug() << "OneWayDelegate: 无有效 QueryResult 数据";
            status = true;
            p1 = index.data(target_role).value<QueryResult*>();
        }
        if (!p1) {
            painter->restore();
            qDebug() << "OneWayDelegate: 无有效 QueryResult 数据";
            return;
        }
        painter->save();
        //QueryResult* p1 = index.data(target_role).value<QueryResult*>();
        if (!p1) {
            painter->restore();
            qDebug()<<"Fail";
            return;
        }
        const QRect itemRect = option.rect;

        // --- 1. 准备字体和颜色 ---
        QPalette palette = option.palette;
        if (option.state & QStyle::State_Selected) {
            painter->fillRect(itemRect, palette.highlight());
            palette.setColor(QPalette::Text, palette.highlightedText().color());
            palette.setColor(QPalette::ButtonText, palette.highlightedText().color()); // 选中时按钮文本变白
        }
        QColor textColor = palette.color(QPalette::Text);
        QColor seatColor = QColor("#2ECC71"); // 有票绿色
        if (option.state & QStyle::State_Selected) {
            seatColor = Qt::white; // 选中时座位文本也变白
        }

        // --- 2. 调整布局：预留按钮空间（核心修改）---
        // 总可用宽度 = item宽度 - 左右padding - 4个区域间距（发车-车次、车次-到达、到达-座位、座位-按钮）
        int totalAvailableWidth = itemRect.width() - 2 * m_padding - 4 * m_spacing;
        if (totalAvailableWidth < 150) { // 防止宽度过小导致布局错乱
            totalAvailableWidth = 150;
        }

        // 按比例分配宽度（前3个区域比例不变，剩余宽度拆分座位区和按钮区）
        int departWidth = static_cast<int>(totalAvailableWidth * 0.20); // 20% 发车区
        int trainWidth = static_cast<int>(totalAvailableWidth * 0.25);  // 25% 车次区
        int arriveWidth = static_cast<int>(totalAvailableWidth * 0.20); // 20% 到达区
        int remainingWidth = totalAvailableWidth - departWidth - trainWidth - arriveWidth; // 剩余35%
        int seatWidth = remainingWidth - m_btnWidth - m_spacing; // 座位区宽度 = 剩余宽度 - 按钮宽度 - 间距
        if (seatWidth < 100) seatWidth = 100; // 座位区最小宽度限制

        // 计算各区域位置（新增按钮区 btnArea）
        QRect departArea = QRect(itemRect.x() + m_padding, itemRect.y() + m_padding, departWidth, itemRect.height() - 2 * m_padding);
        QRect trainArea = QRect(departArea.right() + m_spacing, departArea.top(), trainWidth, departArea.height());
        QRect arriveArea = QRect(trainArea.right() + m_spacing, departArea.top(), arriveWidth, departArea.height());
        QRect seatArea   = QRect(arriveArea.right() + m_spacing, departArea.top(), seatWidth, departArea.height());
        // 按钮区：座位区右侧 + 间距，垂直居中（固定宽高）
        QRect btnArea    = QRect(seatArea.right() + m_spacing,
                              departArea.top() + (departArea.height() - m_btnHeight) / 2,
                              m_btnWidth, m_btnHeight);

        // --- 3. 绘制原有内容（发车区、车次区、到达区、座位区）---
        QFontMetrics timeFm(m_timeFont);
        QFontMetrics stationFm(m_stationFont);
        QFontMetrics trainFm(m_trainFont);
        QFontMetrics seatFm(m_seatFont);

        // 3.1 绘制发车区（不变）
        painter->setFont(m_timeFont);
        painter->setPen(textColor);
        QString departTime = p1->SetOutTime.time().toString("hh:mm");
        painter->drawText(departArea, Qt::AlignTop | Qt::AlignLeft, departTime);

        painter->setFont(m_stationFont);
        QRect startTagRect(departArea.x(), departArea.bottom() - m_tagSize.height(), m_tagSize.width(), m_tagSize.height());
        painter->setBrush(QColor("#FF9900"));
        painter->setPen(Qt::NoPen);
        painter->drawRect(startTagRect);
        painter->setPen(Qt::white);
        painter->drawText(startTagRect, Qt::AlignCenter, "始");

        painter->setPen(textColor);
        QString source = p1->Source;
        int textX = startTagRect.right() + 5;
        int textY = departArea.bottom() - (m_tagSize.height() - stationFm.height()) / 2;
        painter->drawText(textX, textY, source);

        // 3.2 绘制车次区（不变）
        painter->setFont(m_trainFont);
        painter->setPen(textColor);
        QString id = p1->Id;
        QString elidedId = trainFm.elidedText(id, Qt::ElideRight, trainArea.width() - 5); // 留出边距
        painter->drawText(trainArea, Qt::AlignTop | Qt::AlignLeft, elidedId);

        // 3.3 绘制到达区（不变）
        painter->setFont(m_timeFont);
        painter->setPen(textColor);
        QString arriveTime = p1->ArriveTime.time().toString("hh:mm");
        painter->drawText(arriveArea, Qt::AlignTop | Qt::AlignLeft, arriveTime);

        painter->setFont(m_stationFont);
        QRect passTagRect(arriveArea.x(), arriveArea.bottom() - m_tagSize.height(), m_tagSize.width(), m_tagSize.height());
        painter->setBrush(QColor("#666666"));
        painter->setPen(Qt::NoPen);
        painter->drawRect(passTagRect);
        painter->setPen(Qt::white);
        painter->drawText(passTagRect, Qt::AlignCenter, "过");

        painter->setPen(textColor);
        QString dest = p1->Destination;
        textX = passTagRect.right() + 5;
        textY = arriveArea.bottom() - (m_tagSize.height() - stationFm.height()) / 2;
        painter->drawText(textX, textY, dest);

        // 3.4 绘制座位区（不变，宽度已调整）
        painter->setFont(m_seatFont);
        painter->setPen(seatColor);
        int seatY = seatArea.top() + (seatArea.height() - seatFm.height()) / 2; // 垂直居中

        if(HighSpeedResult* result = dynamic_cast<HighSpeedResult*>(p1)){
            QString secondClass = QString("二等 %1").arg(result->SecondClassCnt);
            QString firstClass = QString("一等 %1").arg(result->FirstClassCnt);
            painter->drawText(seatArea.x(), seatY, secondClass);
            painter->drawText(seatArea.x() + seatArea.width()/2, seatY, firstClass);
        } else if(QuickTrainResult* result = dynamic_cast<QuickTrainResult*>(p1)){
            QString hardSeat = QString("硬座 %1").arg(result->HardSeatCnt);
            QString hardBed = QString("硬卧 %1").arg(result->HardBedCnt);
            QString softBed = QString("软卧 %1").arg(result->SoftBedCnt);
            int col1 = seatArea.x();
            int col2 = seatArea.x() + seatArea.width()/3;
            int col3 = seatArea.x() + 2*seatArea.width()/3;
            painter->drawText(col1, seatY, hardSeat);
            painter->drawText(col2, seatY, hardBed);
            painter->drawText(col3, seatY, softBed);
        } else if(FlightResult* result = dynamic_cast<FlightResult*>(p1)){
            QString economy = QString("经济舱 %1").arg(result->EconomyClassCnt);
            QString firstClass = QString("头等舱 %1").arg(result->FirstClassCnt);
            painter->drawText(seatArea.x(), seatY, economy);
            painter->drawText(seatArea.x() + seatArea.width()/2, seatY, firstClass);
        }

        // --- 4. 新增：绘制「预订」按钮（核心修改）---
        if(status){
        QStyleOptionButton btnOpt;
        btnOpt.initFrom(option.widget); // 继承父组件样式（适配系统主题）
        btnOpt.rect = btnArea;          // 按钮位置和尺寸
        btnOpt.text = m_btnText;        // 按钮文本
        btnOpt.palette = palette;       // 继承颜色（适配选中状态）

        // 设置按钮状态：启用 + hover + 按下
        btnOpt.state |= QStyle::State_Enabled;
        if (index == m_hoverIndex) {
            btnOpt.state |= QStyle::State_MouseOver; // 鼠标悬浮样式
        }
        if (index == m_pressedIndex) {
            btnOpt.state |= QStyle::State_Sunken; // 鼠标按下样式
        }

        // 绘制系统原生风格按钮（自动适配 Windows/macOS/Linux 主题）
        QApplication::style()->drawControl(QStyle::CE_PushButton, &btnOpt, painter);
        }
        painter->restore();
    }

    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override
    {
        Q_UNUSED(option);
        Q_UNUSED(index);

        // 计算高度：基于字体和布局（按钮高度可能大于原有内容，取最大值）
        QFontMetrics timeFm(m_timeFont);
        QFontMetrics stationFm(m_stationFont);
        int contentHeight = timeFm.height() + m_spacing + m_tagSize.height();
        contentHeight = qMax(contentHeight, m_btnHeight); // 确保高度不小于按钮高度

        // 加上上下padding
        int totalHeight = contentHeight + 2 * m_padding;

        // 默认宽度：增加按钮宽度和间距（原550 + 按钮80 + 间距15 = 645）
        int defaultWidth = 645;

        return QSize(defaultWidth, totalHeight);
    }
signals:
    void bookButtonClicked(QueryResult* result);
private:
    int m_padding;
    int m_spacing;
    CustomRoles target_role;
    QSize m_tagSize;

    // 新增：按钮相关配置
    QString m_btnText;
    int m_btnWidth;
    int m_btnHeight;

    QFont m_timeFont;
    QFont m_stationFont;
    QFont m_trainFont;
    QFont m_seatFont;

    // 新增：记录hover和pressed的索引（mutable允许const函数修改）
    mutable QModelIndex m_hoverIndex;
    mutable QModelIndex m_pressedIndex;
    QueryResult* currentResult = nullptr;
};
class OneWayQueryResultModel:public QueryResultModel{
public:
    OneWayQueryResultModel(QueryPackage* cur = nullptr,QObject* parent = nullptr):QueryResultModel(cur,parent){
    }
    QAbstractItemDelegate* getDelegate(QObject *parent)const override{
        return new OneWayDelegate(parent);
    }
    int getRowCount()const override{
        return results.size();
    }
    void setResult(const QJsonObject &json)override{
        beginResetModel();
        const QJsonArray data = json["data"].toArray();
        int page = json["page"].toInt();
        setPage(page);
        qDeleteAll(results);
        for(const auto& it:data){
            if(it.isObject()){
                QJsonObject k = it.toObject();
                k["source"] = current->getSource();
                k["destination"] = current->getDest();
                QueryResult* t = QueryResult::fromJson(k);
                results.append(t);
            }
        }
        endResetModel();
    }
    void Test(){
        beginResetModel();
        results.append(new FlightResult());
        endResetModel();
    }
    QVariant getData(const QModelIndex&index,int role)const override{
        int row = index.row();
        QueryResult* result = results[row];
        switch(role){
        case Qt::DisplayRole:
                 return QString("%1: %2 → %3")
                     .arg(result->Id)
                     .arg(result->Source)
                     .arg(result->Destination);

        case OneWayResultPtrRole:
            return QVariant::fromValue(result);
        default:
            return QVariant();
        }
    }
private:
    QList<QueryResult*> results = {};

};
class RndTripResultModel:public QueryResultModel{
public:
    RndTripResultModel(QueryPackage* cur = nullptr,QObject* parent = nullptr):QueryResultModel(cur,parent){}
    QVariant getData(const QModelIndex &index, int role)const override{
        int row = index.row();
        std::pair<QueryResult*,QueryResult*>result = results[row];
        QueryResult* l1 = result.first;
        QueryResult* l2 = result.second;
        switch(role){
        case Qt::DisplayRole:
            return QString::asprintf("%s\n%s",l1->Id.toUtf8().constData(),l2->Id.toUtf8().constData());
        case RndFirstRole:
            return QVariant::fromValue(l1);
        case RndSecondRole:
            return QVariant::fromValue(l2);
        default:
            return QVariant();
        }
        return QVariant();
    }
    QAbstractItemDelegate* getDelegate(QObject *parent)const override{
        return new OneWayDelegate(parent);
    }

    void setResult(const QJsonObject& json)override{
        beginResetModel();
        const QJsonArray data = json["data"].toArray();
        int page = json["page"].toInt();
        setPage(page);
        for(int i=0;i<results.size();i++){
            delete results[i].first;
            delete results[i].second;
        }
        results.clear();
        // qDebug()<<data.size();
        for(const auto& it:data){
            if(it.isObject()){
                QJsonObject k = it.toObject();
                QJsonObject json;
                json["id"] = k["name"];
                json["source"] = this->current->getSource();
                json["destination"] = this->current->getDest();
                json["starttime"] = k["go_startTime"];
                json["endtime"] = k["go_endTime"];
                json["types"] = k["go_types"];
                json["cnts"] = k["go_cnts"];
                json["prices"] = k["go_prices"];
                QJsonObject json1;
                json1["id"] = k["name"];
                json1["source"] = this->current->getDest();
                json1["destination"] = this->current->getDest();
                json1["starttime"] = k["return_startTime"];
                json1["endtime"] = k["return_endTime"];
                json1["types"] = k["return_types"];
                json1["cnts"] = k["return_cnts"];
                json1["prices"] = k["return_prices"];
                json["type"]=k["type"];
                json1["type"]=k["type"];
                // qDebug()<<k;
                QueryResult* train1 = QueryResult::fromJson(json);
                // qDebug()<<1<<(train1==nullptr);
                QueryResult* train2=nullptr;
                if (k["has_return_ticket"].toBool()) {
                    train2 = QueryResult::fromJson(json1);
                }

                std::pair<QueryResult*,QueryResult*>f = {train1,train2};
                results.append(f);
            }
            // qDebug()<<results.size();
        }
        endResetModel();
    }

    int getRowCount()const override{
        return results.size();
    }
    void Test(){
        beginResetModel();
        std::pair<QueryResult*,QueryResult*>t = {new HighSpeedResult(),new QuickTrainResult()};
        results.append(t);
        endResetModel();
    }
private:
    QList<std::pair<QueryResult*,QueryResult*>>results;
};
class TransferResultModel:public QueryResultModel{
public:
    TransferResultModel(QueryPackage* cur = nullptr,QObject* parent = nullptr):QueryResultModel(cur,parent){}
    void setResult(const QJsonObject&json)override{
        beginResetModel();
        const QJsonArray data = json["data"].toArray();
        int page = json["page"].toInt();
        setPage(page);
        for(int i=0;i<results.size();i++){
            delete results[i].first;
            delete results[i].second;
        }
        results.clear();
        for(const auto& it:data){
            if(it.isObject()){
                QJsonObject k = it.toObject();
                QJsonObject json;
                json["id"] = k["go_train_name"];
                json["source"] = k["go_from"];
                json["destination"] = k["transfer_station"];
                json["starttime"] = k["go_startTime"];
                json["endtime"] = k["go_endTime"];
                json["types"] = k["go_types"];
                json["cnts"] = k["go_cnts"];
                json["prices"] = k["go_prices"];
                QJsonObject json1;
                json1["id"] = k["transfer_train_name"];
                json1["source"] = k["transfer_station"];
                json1["destination"] = k["destination"];
                json1["starttime"] = k["transfer_startTime"];
                json1["endtime"] = k["transfer_endTime"];
                json1["types"] = k["transfer_types"];
                json1["cnts"] = k["transfer_cnts"];
                json["prices"] = k["transfer_prices"];
                QueryResult* train1 = QueryResult::fromJson(json);
                QueryResult* train2 = QueryResult::fromJson(json1);
                std::pair<QueryResult*,QueryResult*>f = {train1,train2};
                results.append(f);
            }
        }
        endResetModel();
    }
    QVariant getData(const QModelIndex &index, int role)const override{
        int row = index.row();
        std::pair<QueryResult*,QueryResult*>result = results[row];
        QueryResult* l1 = result.first;
        QueryResult* l2 = result.second;
        switch(role){
        case Qt::DisplayRole:
            return QString("%1 %2").arg(l1->Id,l2->Id);
        case TransferFirstRole:
            return QVariant::fromValue(l1);
        case TransferSecondRole:
            return QVariant::fromValue(l2);
        default:
            return QVariant();
        }
        return QVariant();
    }
    int getRowCount()const override{
        return results.size();
    }
    void Test(){
        beginResetModel();
        std::pair<QueryResult*,QueryResult*>t = {new HighSpeedResult(),new QuickTrainResult()};
        //qDebug()<<"Here";
        results.append(t);
        qDebug()<<results.size();
        endResetModel();
    }
    QStyledItemDelegate* getDelegate(QObject *parent)const override{
        return new OneWayDelegate(parent);
    }
private:
    QList<std::pair<QueryResult*,QueryResult*>>results;
};

class RefundResultModel:public QueryResultModel{
public:
    RefundResultModel(QueryPackage* cur,QObject*parent=nullptr):QueryResultModel(cur,parent){}
    class OrderDelegate : public QStyledItemDelegate
    {
    public:
        explicit OrderDelegate(QObject *parent = nullptr);

        void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
        QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;

    private:
        void drawCardBackground(QPainter *painter, const QRect &rect, const QStyleOptionViewItem &option) const;
        void drawOrderInfo(QPainter *painter, const QRect &rect, QueryResult* order, const QStyleOptionViewItem &option) const;

        // 布局参数
        int m_margin;
        int m_padding;
        int m_spacing;

        // 字体
        QFont m_titleFont;
        QFont m_contentFont;
        QFont m_smallFont;

        // 颜色
        QColor m_titleColor;
        QColor m_contentColor;
        QColor m_smallTextColor;
        QColor m_separatorColor;
        QColor m_backgroundColor;
        QColor m_selectedBackgroundColor;
    };
    int getRowCount()const override{
        return results.size();
    }
    QVariant getData(const QModelIndex &index, int role)const override{
        int row = index.row();
        QueryResult* result = results[row];
        switch(role){
        case Qt::DisplayRole:
            return QString("%1 %2").arg(result->Source,result->Destination);
        case RefundResultPtrRole:
            return QVariant::fromValue(result);
        default:
            return QVariant();
        }
        return QVariant();
    }
    void setResult(const QJsonObject&json)override{
        beginResetModel();
        const QJsonArray data = json["data"].toArray();
        for(int i=0;i<results.size();i++){
            delete results[i];
        }
        results.clear();
        for(const auto& it:data){
            if(it.isObject()){
                QJsonObject k = it.toObject();
                QueryResult* f = QueryResult::fromJson(k);
                results.append(f);
            }
        }
        endResetModel();
    }
    void Test(){
        RefundResult* r = new RefundResult();
        results.append(r);
    }
    QStyledItemDelegate* getDelegate(QObject *parent)const override{
        return new OrderDelegate(parent);
    }
private:
    QList<QueryResult*>results;
};

#endif // QUERYRESULTMODEL_H
